var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken')
let { tellModel, UsersModel, UsersimageModel, videoModel } = require('../model/model')

const Core = require('@alicloud/pop-core');
/* GET home page. */



//生成验证码
function generateCode() {
  const characters =
    '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHUKLMNOPQRSTUVWXYZ'
  let code = "";
  for (let i = 0; i < 4; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    code += characters[randomIndex];
  }
  return code;
}

function isCodeValid(creationTime) {
  const currentTime = Date.now();
  const expirationTime = 5 * 60 * 1000; // 5分钟的毫秒数
  return currentTime - creationTime <= expirationTime;
}

//获取验证码
router.post('/getCode', async (req, res) => {
  let phoneNumber = req.query.tell;  //前端传递的手机号
  let code = generateCode();  //接收随机生成的验证码
  const client = new Core({
    accessKeyId: 'LTAI5t8SbZbFrN4ziqPbK5fM',   // 替换成自己的 AccessKey ID
    accessKeySecret: '5MWzh7waZtmmGygbTLuMwcYwBdHKJK',   // 替换成自己的 AccessKey Secret
    endpoint: 'https://dysmsapi.aliyuncs.com', // API 访问入口，根据实际情况修改
    apiVersion: '2017-05-25'  // API 版本号，根据实际情况修改
  })

  const params = {
    RegionId: "cn-hangzhou", // 短信服务所在区域，可以参考阿里云文档
    PhoneNumbers: phoneNumber, // 目标手机号码
    SignName: "啄木鸟", // 短信签名名称，需先在阿里云控制台中申请审核通过
    TemplateCode: "SMS_465313870", // 短信模板 CODE，需先在阿里云控制台中申请审核通过
    TemplateParam: JSON.stringify({
      // 短信模板参数，为 JSON 字符串格式
      code: code, // 模板中的变量名和对应的值
    }),
  };
  const requestOption = {
    // 设置请求超时时间等选项
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  };
  try {
    const result = await client.request('SendSms', params, requestOption);
    console.log(result);
    return result;
  } catch (error) {
    console.error(error);
    return error;
  }
})


//login
router.post('/login', async (req, res) => {
  let { tell, password } = req.body;
  let user = await tellModel.find({ tell: tell });
  console.log(user);
  if (user.length > 0) {

    if (user[0].password == password) {
      let short_token = "Bearer" + jwt.sign({ tell: tell }, 'ws', { expiresIn: '1h' });
      let long_token = 'Bearer' + jwt.sign({ tell: tell }, 'ws', { expiresIn: '7d' });
      res.send({
        data: { short_token, long_token, code: 200, msg: "登录成功" },
      })

    } else {
      console.log(111);
      res.send({
        data: {
          code: 400,
          msg: "账号或密码错误，登录失败"
        }
      })
    }
  } else {
    res.send({
      data: {
        code: 401,
        msg: "账号不存在，注册账号后登录"
      }
    })
  }
})


//注册
router.post("/register", async (req, res) => {
  try {
    let body = req.body;
    console.log(body);
    let user = await tellModel.find({ tell: body.tell });
    if (user.length > 0) {
      res.send({
        data: {
          code: 400,
          msg: '账号已存在，请重新输入'
        }
      })
    }else{
      res.send({
        data: {
          code: 200,
          msg: '账号正确'
        }
      })
    }
    if (body.password.length <= 0) {
      res.send({
        data: {
          code: 400,
          msg: '密码过短'
        }
      })
    } else {
      
      await tellModel.create(body)
      res.send({
        data: {
          code: 200,
          msg: '注册成功'
        }
      })
    }
  } catch {

  }

})












router.post('/Userimg', async (req, res) => {
  await UsersimageModel.create(req.body)
  res.send({
    msg: '添加成功'
  })
})

router.post('/Useradd', async (req, res) => {
  await UsersModel.create(req.body)
  res.send({
    msg: '添加成功'
  })
})

router.get('/Userlist', async (req, res) => {
  let list = await UsersModel.find().populate('userid')
  res.send({
    list,
    code: 200
  })
})


//添加视频
router.get('/video', async (req, res) => {
  let { page } = req.query
  console.log(req.query);
  let videos = await videoModel.find()
  videos = videos.slice((page - 1) * 3, page * 3)
  console.log(videos);
  res.send({
    code: 200, videos
  })
})

  

module.exports = router;
